//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package admin_keyword_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas-org/api-server/admin_api_serv/admin_common"
	"atomgit.com/openlinksaas-org/api-server/config"
	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/api-server/utils"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/keyword_api"
	"go.mongodb.org/mongo-driver/mongo"
)

type KeywordAdminApiImpl struct {
	keyword_api.UnimplementedKeywordAdminApiServer
	adminCfg *config.AdminCfg
}

func NewKeywordAdminApiImpl(adminCfg *config.AdminCfg) *KeywordAdminApiImpl {
	return &KeywordAdminApiImpl{adminCfg: adminCfg}
}

func (apiImpl *KeywordAdminApiImpl) Add(ctx context.Context, req *keyword_api.AdminAddRequest) (*keyword_api.AdminAddResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &keyword_api.AdminAddResponse{
			Code:   keyword_api.AdminAddResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &keyword_api.AdminAddResponse{
			Code:   keyword_api.AdminAddResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.KeywordPerm.Add {
		return &keyword_api.AdminAddResponse{
			Code:   keyword_api.AdminAddResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := dao.KeywordDao.Exist(ctx, req.Keyword)
	if err != nil {
		return nil, err
	}
	if exist {
		return &keyword_api.AdminAddResponse{
			Code:   keyword_api.AdminAddResponse_CODE_KEYWORD_EXIST,
			ErrMsg: "关键词已存在",
		}, nil
	}

	nowTime := time.Now().UnixNano() / 1e6

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = dao.KeywordDao.Insert(sessCtx, &dao.KeywordDbItem{
			Keyword:   req.Keyword,
			TimeStamp: nowTime,
		})
		if err != nil {
			return nil, err
		}
		versionItem, err := dao.VersionDao.Get(sessCtx, dao.VERSION_KEY_KEYWORD)
		if err != nil {
			return nil, err
		}
		newVersion := versionItem.Version + 1
		if newVersion == 0 {
			newVersion = 1
		}
		err = dao.VersionDao.Set(sessCtx, dao.VERSION_KEY_KEYWORD, newVersion)
		if err != nil {
			return nil, err
		}
		return &keyword_api.AdminAddResponse{
			Code: keyword_api.AdminAddResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*keyword_api.AdminAddResponse), nil
}

func (apiImpl *KeywordAdminApiImpl) List(ctx context.Context, req *keyword_api.AdminListRequest) (*keyword_api.AdminListResponse, error) {
	emptyList := []*keyword_api.KeywordInfo{}

	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &keyword_api.AdminListResponse{
			Code:        keyword_api.AdminListResponse_CODE_WRONG_SESSION,
			ErrMsg:      "会话不存在",
			KeywordList: emptyList,
		}, nil
	}
	if !sess.AuthOk {
		return &keyword_api.AdminListResponse{
			Code:        keyword_api.AdminListResponse_CODE_NOT_AUTH,
			ErrMsg:      "未授权会话",
			KeywordList: emptyList,
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.KeywordPerm.Read {
		return &keyword_api.AdminListResponse{
			Code:        keyword_api.AdminListResponse_CODE_NO_PERMISSION,
			ErrMsg:      "没有权限",
			KeywordList: emptyList,
		}, nil
	}

	count, err := dao.KeywordDao.Count(ctx, req.FilterBySearchStr, req.SearchStr)
	if err != nil {
		return nil, err
	}
	keywordItemList, err := dao.KeywordDao.List(ctx, req.FilterBySearchStr, req.SearchStr, int64(req.Offset), int64(req.Limit))
	if err != nil {
		return nil, err
	}
	keywordList := []*keyword_api.KeywordInfo{}
	for _, keywordItem := range keywordItemList {
		keyword := keywordItem.ToKeywordInfo()
		keywordList = append(keywordList, keyword)
	}
	return &keyword_api.AdminListResponse{
		Code:        keyword_api.AdminListResponse_CODE_OK,
		TotalCount:  count,
		KeywordList: keywordList,
	}, nil
}

func (apiImpl *KeywordAdminApiImpl) Remove(ctx context.Context, req *keyword_api.AdminRemoveRequest) (*keyword_api.AdminRemoveResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &keyword_api.AdminRemoveResponse{
			Code:   keyword_api.AdminRemoveResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &keyword_api.AdminRemoveResponse{
			Code:   keyword_api.AdminRemoveResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.KeywordPerm.Remove {
		return &keyword_api.AdminRemoveResponse{
			Code:   keyword_api.AdminRemoveResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := dao.KeywordDao.Exist(ctx, req.Keyword)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &keyword_api.AdminRemoveResponse{
			Code: keyword_api.AdminRemoveResponse_CODE_OK,
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = dao.KeywordDao.Remove(sessCtx, req.Keyword)
		if err != nil {
			return nil, err
		}
		versionItem, err := dao.VersionDao.Get(sessCtx, dao.VERSION_KEY_KEYWORD)
		if err != nil {
			return nil, err
		}
		newVersion := versionItem.Version + 1
		if newVersion == 0 {
			newVersion = 1
		}
		err = dao.VersionDao.Set(sessCtx, dao.VERSION_KEY_KEYWORD, newVersion)
		if err != nil {
			return nil, err
		}
		return &keyword_api.AdminRemoveResponse{
			Code: keyword_api.AdminRemoveResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*keyword_api.AdminRemoveResponse), nil
}

func (apiImpl *KeywordAdminApiImpl) Test(ctx context.Context, req *keyword_api.AdminTestRequest) (*keyword_api.AdminTestResponse, error) {
	emptyList := []string{}

	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &keyword_api.AdminTestResponse{
			Code:        keyword_api.AdminTestResponse_CODE_WRONG_SESSION,
			ErrMsg:      "会话不存在",
			KeywordList: emptyList,
		}, nil
	}
	if !sess.AuthOk {
		return &keyword_api.AdminTestResponse{
			Code:        keyword_api.AdminTestResponse_CODE_NOT_AUTH,
			ErrMsg:      "未授权会话",
			KeywordList: emptyList,
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.KeywordPerm.Read {
		return &keyword_api.AdminTestResponse{
			Code:        keyword_api.AdminTestResponse_CODE_NO_PERMISSION,
			ErrMsg:      "没有权限",
			KeywordList: emptyList,
		}, nil
	}

	keywordList, err := utils.CheckKeyWrod(ctx, req.Content)
	if err != nil {
		return nil, err
	}
	return &keyword_api.AdminTestResponse{
		Code:        keyword_api.AdminTestResponse_CODE_OK,
		KeywordList: keywordList,
	}, nil
}
